import { OauthClientDetailsType } from '@/datatypes/oauthClientDetails/data';
import { useOpenPermissions } from '@/hooks/usePermissions';
import { Form, Modal, Transfer } from 'antd';
import React, { useState } from 'react';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<OauthClientDetailsType> & {
    targetKeys?: React.Key[];
  };

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<OauthClientDetailsType>;
};

const AddPermForm: React.FC<UpdateFormProps> = (props) => {
  const openPermissions = useOpenPermissions();

  const initialTargetKeys: React.Key[] | (() => React.Key[]) = [];
  const [form] = Form.useForm<FormValueType>();
  const [targetKeys, setTargetKeys] = useState<React.Key[]>(initialTargetKeys);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);

  const handleOk = async () => {
    await props.onSubmit({ targetKeys });
  };

  const handleChange = (targetKeys: React.Key[]) => {
    setTargetKeys(targetKeys);
  };

  const handleSelectChange = (sourceSelectedKeys: React.Key[], targetSelectedKeys: React.Key[]) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  return (
    <Modal
      width={1200}
      style={{
        padding: '32px 40px 48px',
      }}
      destroyOnClose
      title="授权"
      open={props.updateModalVisible}
      onCancel={() => {
        props.onCancel();
      }}
      onOk={handleOk}
    >
      <Form form={form} initialValues={props.values}>
        <Transfer
          listStyle={{
            width: 500,
            height: 600,
          }}
          dataSource={openPermissions}
          titles={['未得到权限', '已拥有权限']}
          targetKeys={targetKeys}
          selectedKeys={selectedKeys}
          onChange={handleChange}
          onSelectChange={handleSelectChange}
          render={(item) => item.name}
        />
      </Form>
    </Modal>
  );
};

export default AddPermForm;
